import {
  Injectable,
  ComponentFactoryResolver,
  Type,
  Injector,
  ApplicationRef,
  EmbeddedViewRef,
  ComponentRef,
  TemplateRef
} from "@angular/core";
import { Overlay } from "@angular/cdk/overlay";

import { MsgComponent } from "../cpt/msg/msg.component";
import { MatDialog, MAT_DIALOG_DATA, MatSnackBar } from "@angular/material";

@Injectable({
  providedIn: "root"
})
export class MsgService {
  config: any = {
    duration: 3000
  };
  constructor(
    public snackBar: MatSnackBar,
    private componentFactoryResolver: ComponentFactoryResolver,
    private appRef: ApplicationRef,
    private injector: Injector
  ) {}

  success(msg = "msg work"): void {
    this.snackBar.openFromComponent(MsgComponent, {
      duration: this.config.duration,
      panelClass: "eh-msg",
      verticalPosition: "top",
      data: {
        msg: msg,
        type: "success" // error warning
      }
    });
  }

  error(msg = "msg work"): void {
    this.snackBar.openFromComponent(MsgComponent, {
      duration: this.config.duration,
      panelClass: "eh-msg",
      verticalPosition: "top",
      data: {
        msg: msg,
        type: "error" // error warning
      }
    });
  }

  warning(msg = "msg work"): void {
    this.snackBar.openFromComponent(MsgComponent, {
      duration: this.config.duration,
      panelClass: "eh-msg",
      verticalPosition: "top",
      data: {
        msg: msg,
        type: "warning" // error warning
      }
    });
  }

  loading(msg = "msg work"): void {
    this.snackBar.openFromComponent(MsgComponent, {
      duration: this.config.duration,
      panelClass: "eh-msg",
      verticalPosition: "top",
      data: {
        msg: msg,
        type: "loading" // error warning
      }
    });
  }

  createComponentRef(component: any): ComponentRef<any> {
    const componentRef = this.componentFactoryResolver
      .resolveComponentFactory(component)
      .create(this.injector);
    this.appRef.attachView(componentRef.hostView);
    return componentRef;
  }
}
